package com.jeebey.mybatis.query;

import java.util.List;

/**条件查询
 * @since 1.0
 * @author <a href="mailto:84961426@qq.com">JuST4iT</a>
 * @version $Id: Condition.java Feb 18, 2016 6:06:32 PM $
 */
public class Criterion {
	public final static String ASC = "ASC";
	public final static String DESC = "DESC";
	private StringBuffer orderBys = new StringBuffer();
	private StringBuffer pagingBy = new StringBuffer();
	
	private Condition condition = null;

	public Criterion() {
		this(null);
	}
	
	public Criterion(Condition condition) {
		this.condition = condition != null ? condition : new Condition();
	}

	public List<Object> getParams() {
		return this.condition.getParams();
	}
	
	public List<Object> toParams() {
		return this.condition.getParams();
	}

	public String toSQL() {
		return toSQL(true);
	}
	
	public String toSQL(boolean bNeedOrderby) {
		String whereConndition = "";
		if (condition.getBuffer().length() != 0) {
			whereConndition = " WHERE " + condition.getBuffer().toString();
		}

		if (bNeedOrderby==false||orderBys.length() == 0) {
			return whereConndition;
		}
		
		return orderBys.length() == 0 ? whereConndition : whereConndition + " ORDER BY " + orderBys.substring(1);
	}
	
	public String toPagingSQL() {
		String whereConndition = "";
		if (condition.getBuffer().length() != 0) {
			whereConndition = " WHERE " + condition.getBuffer().toString();
		}
		return pagingBy.length() == 0 ? whereConndition : whereConndition + pagingBy.toString();
	}

	public Criterion orderBy(String field, String order) {
		orderBys.append(",").append(field).append(" ").append(order);
		return this;
	}
	
	//暂时只取了mysql
	public<T>Criterion pagingBy(Paging<T> paging){
		pagingBy.append(" LIMIT ").append(paging.getFrom()).append(",").append(paging.getSize());
		return this;
	}
	
	public Criterion pagingBy(String sql){
		pagingBy.append(" ").append(sql);
		return this;
	}
	
	//暂时只取了mysql
	public Criterion pagingBy(Integer iPage,Integer iSize){
		pagingBy.append(" LIMIT ").append((iPage - 1) * iSize).append(",").append(iSize);
		return this;
	}
}

